package com.dh.project.controller;

import com.alibaba.fastjson.JSON;
import com.dh.project.model.*;
import com.dh.project.model.push.PageType;
import com.dh.project.other.ModelRes;
import com.dh.project.service.*;
import com.dh.project.utils.DayuSMSUtil;
import com.dh.project.utils.PageUtil;
import com.dh.project.utils.PushUtil;
import com.dh.project.utils.WorkerPushUtil;
import com.dh.project.view.OrderDetailView;
import com.dh.project.view.OrderListView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/** 订单Controller
 * Created by admin on 2017/4/5.
 */
@Controller
public class OrderController {

    private OrderInfoService orderInfoService;

    private OrderServiceProjectService orderServiceProjectService;

    private EmployeeInfoService employeeInfoService;

    private ServiceProjectService serviceProjectService;

    private IndoorpriceService indoorpriceService;

    private CustomerAddressService customerAddressService;

    @Autowired
    public OrderController(OrderInfoService orderInfoService,OrderServiceProjectService orderServiceProjectService,
                           EmployeeInfoService employeeInfoService,ServiceProjectService serviceProjectService,
                           IndoorpriceService indoorpriceService,CustomerAddressService customerAddressService){
        this.orderInfoService = orderInfoService;
        this.orderServiceProjectService = orderServiceProjectService;
        this.employeeInfoService = employeeInfoService;
        this.serviceProjectService = serviceProjectService;
        this.indoorpriceService = indoorpriceService;
        this.customerAddressService = customerAddressService;
    }

    /**
     * 查询订单列表
     * @param orderListView
     * @param page
     * @param model
     * @return
     */
    @RequestMapping(value = "selectOrderList",produces = "text/html;charset=utf-8")
    public String selectOrderList(OrderListView orderListView, int page, Model model){
        Map map = new HashMap();
        map.put("customer_name",orderListView.getCustomer_name());
        map.put("customer_phone",orderListView.getCustomer_phone());
        map.put("order_type",orderListView.getOrder_type());
        map.put("order_id",orderListView.getOrder_id());
        map.put("order_status",orderListView.getOrder_status());
        map.put("page_start",(page-1)*10);
        map.put("page_end",10);
        List<OrderListView> orderListViewList = orderInfoService.selectOrderListByMap(map);

        model.addAttribute("orderListViewList",orderListViewList);

        PageModel pageModel = orderInfoService.selectOrderListByMapCount(map);
        PageInfo pageInfo = PageUtil.getPageInfo(pageModel,page,10);
        pageInfo.setPage_href(PageUtil.getPageHrefThree(orderListView,1));
        pageInfo.setPage_index(page);
        pageInfo.setPage_count(PageUtil.getPageCount(pageModel.getPage_index(),10));

        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("orderListView",orderListView);
        return "order_list";
    }

    /**
     * 查询订单详情
     * @param orderDetailView
     * @param model
     * @return
     */
    @RequestMapping(value = "selectOrderDetailById",produces = "text/html;charset=utf-8")
    public String selectOrderDetailById(OrderDetailView orderDetailView,  Model model){
        //上部信息
        Map map = new HashMap();
        map.put("order_id",orderDetailView.getOrder_id());
        OrderDetailView orderDetailView1 = orderInfoService.selectOrderDetailViewByMap(map);
        model.addAttribute("orderDetailView",orderDetailView1);

        Map mapEmployee = new HashMap();
        if (orderDetailView1.getOrder_type() == 1){
            mapEmployee.put("employee_type_one",1);
        }
        if (orderDetailView1.getOrder_type() == 2){
            mapEmployee.put("employee_type_two",1);
        }
        if (orderDetailView1.getOrder_type() == 3){
            mapEmployee.put("employee_type_three",1);
        }
        if (orderDetailView1.getOrder_type() == 4){
            mapEmployee.put("employee_type_four",1);
        }
        if (orderDetailView1.getOrder_type() == 5){
            mapEmployee.put("employee_type_five",1);
        }
        if (orderDetailView1.getOrder_type() == 6){
            mapEmployee.put("employee_type_six",1);
        }
        mapEmployee.put("employee_status",1);
        mapEmployee.put("is_freeze",1);
        //可选择工人
        List<EmployeeInfo> employeeInfos = employeeInfoService.selectByMap(mapEmployee);
        model.addAttribute("employeeInfos",employeeInfos);

        //订单工人
        EmployeeInfo employeeInfo = employeeInfoService.selectById(orderDetailView1.getEmployee_id());
        if (employeeInfo == null){
            employeeInfo = new EmployeeInfo();
            employeeInfo.setEmployee_id(0);
        }
        model.addAttribute("employeeInfo",employeeInfo);


        Map serviceMap = new HashMap();
        serviceMap.put("service_class",orderDetailView1.getOrder_type());
        //筛选产品列表
        List<ServiceProject> serviceProjects = serviceProjectService.selectByMap(serviceMap);
        model.addAttribute("serviceProjects",serviceProjects);

        //服务项列表
        List<OrderServiceProject> orderServiceProjectList = orderServiceProjectService.selectByMap(map);
        model.addAttribute("orderServiceProjectList",orderServiceProjectList);
        return "order_detail";
    }

    /**
     * 配单
     * @param OrderInfo
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "updateOrderEmployee",produces = "text/html;charset=utf-8")
    public Object updateOrderEmployee(OrderInfo OrderInfo){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        OrderInfo orderInfo1 = orderInfoService.selectById(OrderInfo.getOrder_id());
        orderInfo1.setEmployee_id(OrderInfo.getEmployee_id());
        //修改状态为 待上门
        orderInfo1.setOrder_status(2);
        boolean isSuccess = orderInfoService.updateById(orderInfo1);
        if (isSuccess){
            //客服配单双方通知
            List<String> aliasList = new ArrayList<>();
            aliasList.add(orderInfo1.getCustomer_id().toString());
            EmployeeInfo employeeInfo = employeeInfoService.selectById(orderInfo1.getEmployee_id());
            PushUtil.pushOne(aliasList, "已为您的订单匹配师傅，工号"+employeeInfo.getEmployee_id().toString()+"；手机号"+employeeInfo.getEmployee_phone()+"，即将准时上门!",JSON.toJSON(new PageType(1,orderInfo1.getOrder_id().toString())));
            aliasList.clear();
            aliasList.add(orderInfo1.getEmployee_id().toString());
            String reverse = sdf.format(Long.parseLong(orderInfo1.getReserve_date()));
            CustomerAddress customerAddress = customerAddressService.selectById(orderInfo1.getHouse_id());
            WorkerPushUtil.pushOne(aliasList, "您有一笔新订单！时间："+reverse+orderInfo1.getReserve_time()+";地址："+customerAddress.getAddress()+customerAddress.getHouse_number()+" 请前往源管家查看详情!",JSON.toJSON(new PageType(1,orderInfo1.getOrder_id().toString())));
            return new ModelRes();
        }else {
            return new ModelRes(ModelRes.Status.ERROR,"配单失败！");
        }
    }

    /*public static void main(String args[]) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        String format = sdf.format(Long.parseLong("1503936000000"));
        Date parse = sdf.parse(format);
        System.out.println(format);
        System.out.println(parse);
    }*/

    /**
     * 删除已配单的订单
     * @param admin_id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "deleteOrderEmployee",produces = "text/html;charset=utf-8")
    public Object deleteOrderEmployee(int admin_id){
        OrderInfo orderInfo1 = orderInfoService.selectById(admin_id);
        orderInfo1.setEmployee_id(0);
        boolean isSuccess = orderInfoService.updateById(orderInfo1);
        if (isSuccess){
            return new ModelRes();
        }else {
            return new ModelRes(ModelRes.Status.ERROR,"删除失败！");
        }
    }

    /**
     * 修改订单
     * @param OrderInfo
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "updateOrderStatus",produces = "text/html;charset=utf-8")
    public Object updateOrderStatus(OrderInfo OrderInfo){

        OrderInfo orderInfo1 = orderInfoService.selectById(OrderInfo.getOrder_id());
        HashMap hm = new HashMap<String, Integer>();
        hm.put("order_id",OrderInfo.getOrder_id());
        Double totalPrice = 0.00;
        List<OrderServiceProject> list = orderServiceProjectService.selectByMap(hm);
        if(list==null||list.size()<1){
            System.out.println("----未发现维保服务---");
        }else {
            for (OrderServiceProject orderServiceProject : list) {
                totalPrice += orderServiceProject.getService_price();
            }
            System.out.println("----发现维保服务---");
        }
          BigDecimal total = BigDecimal.valueOf(totalPrice);
        orderInfo1.setOrder_status(OrderInfo.getOrder_status());
        orderInfo1.setReserve_date(OrderInfo.getReserve_date());
        if(OrderInfo.getIsInsurance()==0){
           Double price = indoorpriceService.selectById(1).getIndoor_price();
            orderInfo1.setIndoor_price(price);
            BigDecimal p = BigDecimal.valueOf(price);
            orderInfo1.setIsInsurance(0);
            orderInfo1.setOrder_price(total.add(p));
            System.out.println("----feiweibao -----");
        }else if(OrderInfo.getIsInsurance()==1){
            System.out.println("----weibao -----");
            orderInfo1.setIndoor_price(0);
            orderInfo1.setIsInsurance(1);
            orderInfo1.setOrder_price(total);
        }
        String ordertime = OrderInfo.getReserve_time().replace("：",":");
        orderInfo1.setReserve_time(ordertime.replaceAll(" ",""));
        boolean isSuccess = orderInfoService.updateById(orderInfo1);
        com.dh.project.model.OrderInfo orderInfo2 = orderInfoService.selectById(orderInfo1.getOrder_id());
        if (isSuccess){

            if(orderInfo2.getOrder_status()==1){
                List<String> aliasList = new ArrayList<>();
                aliasList.add(orderInfo2.getCustomer_id().toString());
                PushUtil.pushOne(aliasList, "正在为你匹配专业师傅，请稍后!",JSON.toJSON(new PageType(1,orderInfo2.getOrder_id().toString())));

            }else if(orderInfo2.getOrder_status()==3){
                List<String> aliasList = new ArrayList<>();
                aliasList.add(orderInfo2.getCustomer_id().toString());
                PushUtil.pushOne(aliasList, "师傅已到达您的报修地址，向师傅详细描述下您的设备问题吧。",JSON.toJSON(new PageType(1,orderInfo2.getOrder_id().toString())));
                aliasList.clear();
                aliasList.add(orderInfo2.getEmployee_id().toString());
                WorkerPushUtil.pushOne(aliasList, "订单"+orderInfo2.getOrder_id()+"；客户已确认您到达目的地。请查看订单并开始检修！",JSON.toJSON(new PageType(1,orderInfo2.getOrder_id().toString())));
            }else if(orderInfo2.getOrder_status()==4){
                List<String> aliasList = new ArrayList<>();
                aliasList.add(orderInfo2.getCustomer_id().toString());
                PushUtil.pushOne(aliasList, "本次维修需要如下配件，请您确认!!",JSON.toJSON(new PageType(1,orderInfo2.getOrder_id().toString())));
            }else if(orderInfo2.getOrder_status()==7){
                List<String> aliasList = new ArrayList<>();
                aliasList.add(orderInfo2.getCustomer_id().toString());
                PushUtil.pushOne(aliasList, "支付成功！写个评价鼓励一下师傅吧!",JSON.toJSON(new PageType(1,orderInfo2.getOrder_id().toString())));

            }else if(orderInfo2.getOrder_status()==5){
                List<String> aliasList = new ArrayList<>();
                aliasList.add(orderInfo2.getCustomer_id().toString());
                PushUtil.pushOne(aliasList, "当师傅维修完成后，请您注意开机验收后付款!",JSON.toJSON(new PageType(1,orderInfo2.getOrder_id().toString())));
            }else if(orderInfo2.getOrder_status()==6){
                List<String> aliasList = new ArrayList<>();
                aliasList.add(orderInfo2.getCustomer_id().toString());
                PushUtil.pushOne(aliasList, "现金支付请求成功，请付款后等待师傅确认!",JSON.toJSON(new PageType(1,orderInfo2.getOrder_id().toString())));
            }else if(orderInfo2.getOrder_status()==8){
                List<String> aliasList = new ArrayList<>();
                aliasList.add(orderInfo2.getEmployee_id().toString());
                CustomerAddress customerAddress = customerAddressService.selectById(orderInfo2.getHouse_id());
                WorkerPushUtil.pushOne(aliasList, "您的"+orderInfo2.getOrder_id()+"号订单，地址为"+customerAddress.getAddress()+customerAddress.getHouse_number()+"，现已被用户撤销，请查看订单详情。!",JSON.toJSON(new PageType(1,orderInfo2.getOrder_id().toString())));

            }
            //修改订单后推送
           /* List<String> aliasList = new ArrayList<>();
            aliasList.add(orderInfo1.getCustomer_id().toString());
            PushUtil.pushOne(aliasList, "您的订单已被客服修改，请点击查看详情!", JSON.toJSON(new PageType(1,orderInfo1.getOrder_id().toString())));
           if(orderInfo1.getEmployee_id()!=null && orderInfo1.getEmployee_id()!=0) {
               aliasList.clear();
               aliasList.add(orderInfo1.getEmployee_id().toString());
               WorkerPushUtil.pushOne(aliasList, "您的配单已被客服修改，请点击查看详情!", JSON.toJSON(new PageType(1, orderInfo1.getOrder_id().toString())));
           }*/
           return new ModelRes();
        }else {
            return new ModelRes(ModelRes.Status.ERROR,"修改失败！");
        }
    }

    /**
     * 订单添加服务项
     * @param order_id
     * @param service_id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "orderAddServiceProjectAAA",produces = "text/html;charset=utf-8")
    public Object orderAddServiceProjectAAA(int order_id ,int service_id){
        OrderInfo orderInfo = orderInfoService.selectById(order_id);
        ServiceProject serviceProject = serviceProjectService.selectById(Long.valueOf(service_id));
        OrderServiceProject orderServiceProject = new OrderServiceProject();
        orderServiceProject.setOrder_id(order_id);
        orderServiceProject.setService_id(service_id);
        orderServiceProject.setService_name(serviceProject.getService_name());
        orderServiceProject.setService_price(serviceProject.getService_all_price().doubleValue());
        orderServiceProject.setCreatetime(String.valueOf(new Date().getTime()));
        orderServiceProject.setModifytime(String.valueOf(new Date().getTime()));
        boolean isSuccess = orderServiceProjectService.insert(orderServiceProject);
        if (isSuccess){
            orderInfo.setOrder_price(BigDecimal.valueOf(orderInfo.getOrder_price().doubleValue()+serviceProject.getService_all_price().doubleValue()));
//            orderInfo.setOrder_status(4);
            orderInfoService.updateById(orderInfo);
            return new ModelRes();
        }else {
            return new ModelRes(ModelRes.Status.ERROR,"添加服务项失败");
        }
    }


    /**
     * 工人删除订单服务项
     * @param service_id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "deleteOrderServiceProject",produces = "text/html;charset=utf-8")
    public Object deleteOrderServiceProject(int order_id,int service_id) {
        OrderInfo orderInfo = orderInfoService.selectById(order_id);
        OrderServiceProject orderServiceProject = orderServiceProjectService.selectById(service_id);
        orderInfo.setOrder_price(BigDecimal.valueOf(orderInfo.getOrder_price().doubleValue() - orderServiceProject.getService_price()));
        if (orderInfo.getOrder_status() != 3 && orderInfo.getOrder_status() != 5){
            return new ModelRes(ModelRes.Status.ERROR,"现订单状态不能删除服务项！");
        }
        orderInfo.setOrder_status(4);
        orderInfoService.updateById(orderInfo);
        boolean isSuccess = orderServiceProjectService.deleteById(service_id);
        if (isSuccess){
           /* List<String> aliasList = new ArrayList<>();
            aliasList.add(orderInfo.getCustomer_id().toString());
            WorkerPushUtil.pushOne(aliasList, "您的订单服务项已被客服删除，请点击查看详情!", JSON.toJSON(new PageType(1,orderInfo.getOrder_id().toString())));
            if(orderInfo.getEmployee_id()!=null && orderInfo.getEmployee_id()!=0) {
                aliasList.clear();
                aliasList.add(orderInfo.getEmployee_id().toString());
                WorkerPushUtil.pushOne(aliasList, "您的配单服务项已被客服删除，请点击查看详情!", JSON.toJSON(new PageType(1, orderInfo.getOrder_id().toString())));
            }*/
            return new ModelRes();
        }else {
            return new ModelRes(ModelRes.Status.ERROR,"删除失败");
        }
    }

}
